package com.joymart.common.error.handling;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Map;
import java.util.Optional;

@ControllerAdvice
@Slf4j
public class JoymartExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(JoymartBusinessException.class)
    public ResponseEntity<Object> handleBusinessExceptions(RuntimeException exception, WebRequest webRequest) {
        Map<String, Object> response = Map.of("message", exception.getMessage());
        ResponseEntity<Object> entity = new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        return entity;
    }


    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<Object> handleBusinessExceptions(AccessDeniedException exception, WebRequest webRequest) {
        Map<String, Object> response = Map.of("message","暂无权限" );
        ResponseEntity<Object> entity = new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
        return entity;
    }



    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Object> handleExceptions(RuntimeException exception, WebRequest webRequest) {
        Map<String, Object> response = Map.of("message", Optional.ofNullable(exception.getMessage()).orElse(""));
        log.warn("error",exception);
        ResponseEntity<Object> entity = new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        return entity;
    }
}
